package com.klun.concTrueWar.five;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 使用 FutureTask 提前加载稍后需要的数据
 */
public class Preloader {
    // ......
    private final FutureTask<ProductInfo> future = new FutureTask<ProductInfo>(new Callable<ProductInfo>() {
        @Override
        public ProductInfo call() throws Exception {
            return loadProductInfo();
        }

    });
    private final Thread thread = new Thread(future);

    public void start(){
        thread.start();
    }
    public ProductInfo get() throws ExecutionException, InterruptedException {
        try{
            return future.get();
        } catch (ExecutionException e){
            Throwable cause = e.getCause();
            if(cause instanceof RuntimeException){
                throw (RuntimeException)cause;
            }else if(cause instanceof Error)
                throw (Error)cause;
            else
                throw new IllegalStateException("Not unchecked",cause);
        }
    }

    private ProductInfo loadProductInfo() {
        return null;
    }
}
class ProductInfo{
    //...
}